package com.zds.support.base

import android.app.Activity
import android.app.Dialog
import android.content.DialogInterface
import android.content.res.Configuration
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.annotation.UiThread
import androidx.appcompat.app.AppCompatActivity
import com.zds.support.R
import com.zds.support.dialog.CommonDialog
import com.zds.support.util.FastClickUtils
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
import java.lang.ref.WeakReference

/**
 *
 */
abstract class SupportBaseActivity : AppCompatActivity(), View.OnClickListener, EasyPermissions.PermissionCallbacks {
    protected var umengPageViewName = ""
    protected val mActivity by lazy { this }
    protected val mWrActivity by lazy { WeakReference<Activity>(mActivity) }
    protected val mOnClickListener by lazy { this }
    protected var mToast: Toast? = null
    protected lateinit var application: SupportBaseApplication

    protected val mLoadingDialog: Dialog by lazy { getLoadingDialog() };
    private var progressDialogMsg = ""
    protected val singleDialog: CommonDialog by lazy {
        CommonDialog.Builder(mActivity)
                .setSingleButtonText(R.string.confirm)
                .setOnClickListener { dialog, isPositive -> dialog.dismiss() }
                .create()
    }
    protected var pageSize = 20
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        application = getApplication() as SupportBaseApplication
        application?.onActivityCreated(mWrActivity)

        onBeforeSetContentLayout()
        onSetContentView()
        initActionBarView()
        initView()
        initData()
    }
    open fun getLoadingDialog(): Dialog {
        return Dialog(this) //TODO 按需求更改loading布局
    }

    open fun onBeforeSetContentLayout() {

    }

    open fun initActionBarView() {

    }

    abstract fun onSetContentView()
    abstract fun initView()
    abstract fun initData()

    override fun onResume() {
        super.onResume()
    }

    override fun onPause() {
        super.onPause()
    }

    override fun onStop() {
        super.onStop()

    }

    override fun onDestroy() {
        application?.onActivityDestroyed(mWrActivity)
        super.onDestroy()

    }

    override fun onLowMemory() {
        super.onLowMemory()
    }

    fun setViewsClickListener(vararg views: View) {
        for (view in views) {
            view.setOnClickListener(mOnClickListener)
        }
    }

    override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) {
        // 兼容androidX在部分手机切换语言失败问题
        if (overrideConfiguration != null) {
            val uiMode = overrideConfiguration.uiMode;
            overrideConfiguration.setTo(getBaseContext().getResources().getConfiguration());
            overrideConfiguration.uiMode = uiMode;
        }
        super.applyOverrideConfiguration(overrideConfiguration);
    }

    open fun toast(msg: String, duration: Int) {
        try {
            mToast = Toast.makeText(mActivity, msg, duration)
            mToast?.setGravity(Gravity.CENTER, 0, 0)
            mToast?.show()
        } catch (e: Exception) {

        }
    }

    fun toast(msg: String) {
        toast(msg, Toast.LENGTH_SHORT)
    }

    fun toast(@StringRes textResId: Int) {
        toast(textResId, Toast.LENGTH_SHORT)
    }

    open fun toast(@StringRes textResId: Int, duration: Int) {
        toast(getString(textResId), duration)
    }

    @UiThread
    fun showProgressDialog(msg: String) {
        try {
            progressDialogMsg = msg
            showProgressDialog(msg, true)
        } catch (e: Exception) {

        }

    }

    @UiThread
    fun showProgressDialog(@StringRes msgId: Int) {
        try {
            progressDialogMsg = getString(msgId)
            showProgressDialog(msgId, true)
        } catch (e: Exception) {

        }

    }

    @UiThread
    fun dismissProgressDialog() {
        try {
            if (mLoadingDialog.isShowing&&!mActivity.isFinishing) {
                mLoadingDialog.dismiss()
            }
        } catch (e: Exception) {

        }

    }

    @UiThread
    fun setProgressDialogMsg(msg: String) {
        try {
            if (!TextUtils.equals(msg, progressDialogMsg)) {
                progressDialogMsg = msg
                mLoadingDialog.setTitle(msg)
            }

        } catch (e: Exception) {

        }
    }

    @UiThread
    fun setProgressDialogMsg(@StringRes msgRes: Int) {
        try {
            val msg = getString(msgRes)
            setProgressDialogMsg(msg)
        } catch (e: Exception) {
        }
    }

    @UiThread
    fun showProgressDialog(msg: String, cancelable: Boolean) {
        try {
            if(!mActivity.isFinishing){ //fix Unable to add window -- token android.os.BinderProxy
                mLoadingDialog.setTitle(msg)
                mLoadingDialog.setCanceledOnTouchOutside(cancelable)
                mLoadingDialog.show()
            }

        } catch (e: Exception) {

        }


    }

    @UiThread
    fun showProgressDialog(@StringRes msgId: Int, cancelable: Boolean) {
        showProgressDialog(getString(msgId), cancelable)
    }

    @UiThread
    fun showSingleDialog(msg: String) {
        showSingleDialog("", msg)
    }

    @UiThread
    fun showSingleDialog(@StringRes msgRes: Int) {
        showSingleDialog("", getString(msgRes))
    }

    @UiThread
    fun showSingleDialog(@StringRes titleRes: Int, @StringRes msgRes: Int) {
        showSingleDialog(getString(titleRes), getString(msgRes))

    }

    @UiThread
    fun showSingleDialog(@StringRes titleRes: Int, @StringRes msgRes: Int,
                         onClickListener: (dialog: DialogInterface, isPositive: Boolean) -> Unit) {
        showSingleDialog(getString(titleRes), getString(msgRes), onClickListener)

    }

    @UiThread
    fun showSingleDialog(title: String, msg: String) {
        showSingleDialog(title, msg, { dialog, isPositive -> })
    }

    @UiThread
    open fun showSingleDialog(title: String, msg: String,
                         onClickListener: (dialog: DialogInterface, isPositive: Boolean) -> Unit) {
        try {
            singleDialog.show()
            singleDialog.setTitle(title)
            singleDialog.setMessage(msg)
            singleDialog.setOnClickListener(onClickListener)
        } catch (e: Exception) {

        }
    }

    @UiThread
    fun showSingleDialog(@StringRes titleRes: Int, msg: String) {
        showSingleDialog(getString(titleRes), msg)
    }

    override fun onRequestPermissionsResult(requestCode: Int,
                                            permissions: Array<out String>,
                                            grantResults: IntArray) {
        // super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //将请求结果传递EasyPermission库处理
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            AppSettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> onBackPressed()
            else -> return super.onOptionsItemSelected(item)
        }
        return true
    }

    open fun onViewClick(v: View) {

    }

    final override fun onClick(v: View?) {
        if (v != null && !FastClickUtils.isFastClick()) {
            onViewClick(v)
        }
    }
}